﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;

namespace GlobalizationTools.ViewModel
{
    public class DataGridImageColumn : DataGridBoundColumn
    {
        public static readonly DependencyProperty StretchProperty;

        static DataGridImageColumn()
        {
            StretchProperty = Image.StretchProperty.AddOwner(typeof(DataGridImageColumn), new FrameworkPropertyMetadata(Stretch.Uniform, FrameworkPropertyMetadataOptions.Inherits, new PropertyChangedCallback(DataGridImageColumn.NotifyPropertyChangeForRefreshContent)));
            DataGridBoundColumn.IsReadOnlyProperty.OverrideMetadata(typeof(DataGridImageColumn), new FrameworkPropertyMetadata(true));
        }

        protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
        {
            return null;
        }

        protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
        {
            Image image = new Image();
            this.ApplyStyle(false, false, image);
            this.ApplyBinding(image, Image.SourceProperty);
            return image;
        }

        internal void ApplyBinding(DependencyObject target, DependencyProperty property)
        {
            BindingBase binding = this.Binding;
            if (binding != null)
            {
                BindingOperations.SetBinding(target, property, binding);
            }
            else
            {
                BindingOperations.ClearBinding(target, property);
            }
        }

        internal void ApplyStyle(bool isEditing, bool defaultToElementStyle, FrameworkElement element)
        {
            Style style = this.PickStyle(isEditing, defaultToElementStyle);
            if (style != null)
            {
                element.Style = style;
            }
        }

        private Style PickStyle(bool isEditing, bool defaultToElementStyle)
        {
            Style style = isEditing ? this.EditingElementStyle : this.ElementStyle;
            if ((isEditing && defaultToElementStyle) && (style == null))
            {
                style = this.ElementStyle;
            }
            return style;
        }

        internal static void NotifyPropertyChangeForRefreshContent(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((DataGridImageColumn)d).NotifyPropertyChanged(e.Property.Name);
        }

    }
}
